<template>
  <div>
    <div v-if="device !== 'mobile'" class="app-container">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline"
               v-hasPermi="['after:serve:query']">
        <el-form-item label="单位" prop="clientName">
          <el-input v-model.trim="queryParams.clientName" :maxlength="15" size="small"
                    placeholder="请输入单位名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" size="small" clearable filterable placeholder="请选择类型"
                     style="width: 100%;">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" v-hasPermi="['after:serve:query']"
                     @click="searchHandler">查询
          </el-button>
          <el-button icon="el-icon-refresh-right" size="mini" v-hasPermi="['after:serve:query']"
                     @click="resetHandler">重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="grid-content bg-purple">
        <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['after:serve:add']"
                   @click="openDialog(null)">增加
        </el-button>
      </div>
      <el-table ref="tableRef" :data="tableData" highlight-current-row max-height="680" v-loading="loading"
                v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
        <!--        <el-table-column type="expand" label="展开">-->
        <!--          <template slot-scope="scope">-->
        <!--            <div class=" img-box" v-if="scope.row.image.length > 2">-->
        <!--              <div v-for="(url, i) in (scope.row.image.split(','))" :key="i">-->
        <!--                <el-image lazy style="width: 160px; height: auto;" fit="contain" :src="env + url"-->
        <!--                          @click="handlePictureCardPreview(url)">-->
        <!--                  <div slot="error" class="image-slot">-->
        <!--                    <i class="el-icon-picture-outline"></i>-->
        <!--                  </div>-->
        <!--                </el-image>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--            <div class=" img-box justify-content" v-else>无</div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column type="index" width="50" align="center" label="序号">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column property="type" label="事件类型" align="center" width="180"/>
        <el-table-column property="clientName" label="单位" align="center"/>
        <el-table-column property="contactName" label="联系人" align="center"/>
        <el-table-column property="contactPhone" label="联系电话" align="center"/>
        <el-table-column property="product" label="产品名称" align="center"/>
        <el-table-column property="status" label="状态" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_workorder_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column property="remark" label="描述信息" align="center" width="160"/>
        <el-table-column property="image" label="查看图片" align="center" width="160">
          <template slot-scope="scope">
            <div class=" img-box" v-if="scope.row.image.length > 2">
              <div>
                <el-image lazy
                          style="width: 100%; height: auto;"
                          fit="contain"
                          :src="env + scope.row.image.split(',')[0]"
                          :preview-src-list="scope.row.image.split(',').map(i=> (env + i))"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </div>
            <div class=" img-box justify-content" v-else>无</div>
          </template>
        </el-table-column>
        <el-table-column property="createBy" label="创建人" align="center" width="120"/>
        <el-table-column property="createTime" label="创建时间" align="center" width="160" sortable/>
        <el-table-column label="操作" align="center"
                         v-if="$auth.hasPermi('after:serve:edit') || $auth.hasPermi('after:serve:remove') || $auth.hasPermi('after:workorder:add')">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-share" v-hasPermi="['after:serve:edit']"
                       @click="relevanceDialog(scope.row)">关联工单
            </el-button>
            <el-button v-if="!scope.row.workorderId" type="text" icon="el-icon-edit"
                       v-hasPermi="['after:workorder:add']"
                       @click="createOrderDialog(scope.row)">创建工单
            </el-button>
            <el-button type="text" icon="el-icon-edit" v-hasPermi="['after:serve:edit']"
                       @click="openDialog(scope.row)">修改
            </el-button>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                           @confirm="deleteHandler(scope.row)">
              <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['after:serve:remove']"
                         type="text" style="margin-left: 10px">删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>

    <div v-else style="height: calc(100vh - 90px);overflow: auto;" class="infinite-box app-container">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline"
               v-hasPermi="['after:serve:query']">
        <el-form-item label="单位" prop="clientName">
          <el-input v-model.trim="queryParams.clientName" :maxlength="15" size="small"
                    placeholder="请输入单位名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" size="small" clearable filterable placeholder="请选择类型"
                     style="width: 100%;">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" v-hasPermi="['after:serve:query']"
                     @click="searchHandler">查询
          </el-button>
          <el-button icon="el-icon-refresh-right" size="mini" v-hasPermi="['after:serve:query']"
                     @click="resetHandler">重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="grid-content bg-purple">
        <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['after:serve:add']"
                   @click="openDialog(null)">增加
        </el-button>
      </div>

      <ul class="infinite-list" v-infinite-scroll="handleLoad">
        <li v-for="item in tableData" :key="item.id" class="infinite-list-item">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ item.type }}</span>
              <div style="float: right;">
                <el-button type="text" v-hasPermi="['after:serve:edit']"
                           @click="relevanceDialog(item)" style="padding: 3px 0">关联工单
                </el-button>
                <el-button v-if="!item.workorderId" type="text"
                           v-hasPermi="['after:workorder:add']"
                           @click="createOrderDialog(item)" style="padding: 3px 0">创建工单
                </el-button>
                <el-button type="text" v-hasPermi="['after:serve:edit']"
                           @click="openDialog(item)" style="padding: 3px 0">修改
                </el-button>
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                               @confirm="deleteHandler(item)">
                  <el-button slot="reference" v-hasPermi="['after:serve:remove']"
                             type="text" style="margin-left: 10px;padding: 3px 0">删除
                  </el-button>
                </el-popconfirm>
              </div>
            </div>
            <div class=" cus_text">
              <div class="flex">
                <span>单位名称: </span>
                <span class="flex-1">{{ item.clientName }}</span>
              </div>
              <div class="flex">
                <span>联系人: </span>
                <span class="flex-1">{{ item.contactName }}</span>
              </div>
              <div class="flex">
                <span>联系电话: </span>
                <span class="flex-1">{{ item.contactPhone }}</span>
              </div>
              <div class="flex items-center">
                <span>状态: </span>
                <div class="flex-1">
                  <dict-tag :options="dict.type.sys_workorder_status" :value="item.status"/>
                </div>
              </div>
              <div class="flex">
                <span>产品名称: </span>
                <span class="flex-1">{{ item.product }}</span>
              </div>
              <div class="flex" v-if="item.remark">
                <span>描述信息: </span>
                <span class="flex-1">{{ item.remark }}</span>
              </div>
              <div class="flex" v-if="item.image.length > 2">
                <span>查看图片: </span>
                <div class="flex-1">
                  <el-image lazy
                            style="width: 50px; height: auto;"
                            fit="contain"
                            :src="env + item.image.split(',')[0]"
                            :preview-src-list="item.image.split(',').map(i=> (env + i))"
                  >
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
              </div>
            </div>
          </el-card>
        </li>
      </ul>

      <div v-if="loading" style="text-align: center;color: #909399;"><i class="el-icon-loading"></i> 正在加载</div>
      <div v-else-if="tableData.length <= 0" style="text-align: center;color: #909399;">暂无数据</div>
      <div v-else-if="!queryParams.hasNextPage" style="text-align: center;color: #909399;">暂无更多数据</div>

      <el-backtop target=".infinite-box"></el-backtop>
    </div>

    <el-dialog :title="dialogTitle === 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="500px"
               close-on-click-modal
               :fullscreen="device === 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form"
               :label-position="device === 'mobile' ? 'top' : 'right'">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" clearable filterable placeholder="请选择类型" style="width: 100%;">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="clientName">
          <el-input v-model.trim="form.clientName" placeholder="请输入单位名称" :maxLength="50"/>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model.trim="form.contactName" placeholder="请输入联系人名称" :maxLength="10"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model.trim="form.contactPhone" placeholder="请输入联系电话" :maxLength="20"/>
        </el-form-item>
        <el-form-item label="产品名称" prop="product">
          <el-select v-model="form.product" filterable placeholder="请选择产品" style="width: 100%;">
            <el-option v-for="item in productList" :key="item.id" :label="item.productName" :value="item.productName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述信息" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" placeholder="请输入描述信息" :maxLength="500"/>
        </el-form-item>
        <el-form-item label="图片信息">
          <el-upload class="upload-demo" ref="upload" action="#" multiple :limit="9" :on-change="handleChange"
                     :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" accept=".jpg,.jpeg,.png,.gif">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="imgDialogVisible" width="800px" :fullscreen="device === 'mobile'">
      <img width="100%" height="auto" style="object-fit: contain;" :src="imgDialogUrl" alt="">
    </el-dialog>

    <el-dialog title="关联工单" :visible.sync="relevanceVisible" width="1000px" :fullscreen="device === 'mobile'"
               @open="searchHandler2">
      <div>
        <el-form :inline="true" :model="queryParams2" class="demo-form-inline">
          <el-form-item label="单位" prop="name">
            <el-input v-model.trim="queryParams2.name" :maxlength="15" size="small"
                      placeholder="请输入单位名称"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="queryParams2.type" size="small" clearable filterable placeholder="请选择类型"
                       style="width: 100%;">
              <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工单来源" prop="source">
            <el-select v-model="queryParams2.source" size="small" clearable filterable placeholder="请选择类型"
                       style="width: 100%;">
              <el-option v-for="item in projectType" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-search" v-hasPermi="['md:activity:query']"
                       @click="searchHandler2">查询
            </el-button>
          </el-form-item>
        </el-form>

        <el-table :data="tableData2" highlight-current-row max-height="500" v-loading="loading2"
                  v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
          <el-table-column width="50" align="center" label="选择">
            <template v-slot="scope">
              <el-radio v-model="selectedItemId" :label="scope.row.id" @change="handleRowChange(scope.row)">{{
                  ""
                }}
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column type="index" width="50" align="center" label="序号">
            <template slot-scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column property="type" label="工单类型" align="center" width="100"/>
          <el-table-column property="source" label="工单来源" align="center" width="100"/>
          <el-table-column property="name" label="名称" align="center" min-width="120"/>
          <el-table-column property="secondarySector" label="二级部门" align="center" min-width="120"/>
          <el-table-column property="contactName" label="联系人" align="center" width="100"/>
          <el-table-column property="contactPhone" label="联系电话" align="center" width="120"/>
          <el-table-column property="address" label="客户地址" align="center" width="180"/>
          <el-table-column property="product" label="产品名称" align="center" width="120"/>
          <el-table-column property="serviceContent" label="服务内容" align="center"/>
          <el-table-column property="status" label="工单状态" align="center" width="100"/>
          <el-table-column property="planTime" label="计划时间" align="center" width="120"/>
          <el-table-column property="description" label="描述" align="center"/>
          <el-table-column property="principalName" label="负责人" align="center" width="120"/>
          <el-table-column property="synergyName" label="协同人" align="center"/>
          <el-table-column property="finishTime" label="完成时间" align="center" width="120"/>
          <el-table-column property="remark" label="备注" align="center"/>
          <el-table-column property="createBy" label="创建人" align="center" width="120"/>
          <el-table-column property="createTime" label="创建时间" align="center" width="160" sortable/>
        </el-table>

        <pagination v-show="total2 > 0" :total="total2" :page.sync="queryParams2.pageNum"
                    :limit.sync="queryParams2.pageSize" @pagination="getList2"/>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="relevanceVisible = false">取 消</el-button>
        <el-button type="primary" @click="relevanceHandler">确 定</el-button>
      </span>
    </el-dialog>

    <CreateAfterOrder :show.sync="workorderVisible" :info="workorderInfo" @add="addHandler"/>
  </div>
</template>
<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi, uploadImgApi} from "@/api/after/serve";
import {getDataListApi as getWorkorderListApi} from "@/api/after/workorder";
import {getDataListApi as getAllProductApi} from "@/api/crm/md/product";
import CreateAfterOrder from '@/views/components/CreateAfterOrder'
import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import {mapGetters} from 'vuex'
import { throttle } from "@/utils"
// import {Message} from "element-ui";

export default {
  name: 'ServeView',
  dicts: ['sys_workorder_status'],
  components: {CreateAfterOrder},
  data() {
    return {
      workorderInfo: {
        secondarySector: "", // 二级部门
        id: null,
        workorderId: null,
        type: "售后维修", // 工单类型（调试验收、售后走访、现场维修、培训大赛）
        source: "客户", // source工单来源（客户、合作伙伴）
        name: "", // 客户/合作伙伴 名称
        contactName: "", // 联系人名称
        contactPhone: "",
        contactId: null,
        address: "", // 地址
        planTime: "", // 计划时间
        serviceContent: "安装", // 服务内容 安装、维修、走访、培训、大赛
        product: "", // 产品
        image: "",
        remark: "",
        finishTime: "", // 完成时间
        principalId: "", // 负责人ID
        synergyId: "", // 协同人ID
        synergyIds: [],
        principalName: "", // 负责人名称
        synergyName: "", // 协同人名称
        description: "", // 描述
        status: "待分配", // 工单状态：（待分配、已指派、已接受、进行中、已完成、已暂停）
      },
      // 创建工单
      workorderVisible: false,
      // 关联的弹窗
      relevanceVisible: false,
      imgDialogUrl: "",// 预览图链接
      env: process.env.VUE_APP_STATIC_API || '',
      imgDialogVisible: false, // 预览图片的弹框
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: false,
      loading2: true,
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 活动日期
      activityDate: [],
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        id: null,
        workorderId: null,
        type: "售后维修",
        clientName: "",
        contactName: "",
        contactPhone: "",
        product: "",
        image: "",
        remark: "",
        status: "",
      },
      // 工单来源类型
      projectType: [
        {
          value: "客户",
          label: "客户"
        },
        {
          value: "代理商",
          label: "代理商"
        }
      ],
      // 表单的校验规则
      rules: {
        type: [
          {required: true, message: '请选择类型', trigger: 'change'}
        ],
        clientName: [
          {required: true, message: '请输入单位名称', trigger: 'blur'}
        ],
        contactName: [
          {required: true, message: '请输入联系人名称', trigger: 'blur'}
        ],
        contactPhone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'}
        ],
        product: [
          {required: true, message: '请输入产品名称', trigger: 'blur'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        clientName: "", // 创建人 *
        type: null, // 类型 *
        pageNum: 1,
        pageSize: 10,
        pages: 0, // 总页数
        hasNextPage: false, // 还有下一页
      },
      // 表格数据
      tableData2: [],
      // 总数条数
      total2: 0,
      // 查询参数
      queryParams2: {
        source: "", // 工单来源
        name: "", // 创建人 *
        type: null, // 类型 *
        pageNum: 1,
        pageSize: 10,
      },
      // 类型
      typeList: [
        {
          label: "售后维修",
          value: "售后维修"
        },
        {
          label: "订单商城",
          value: "订单商城"
        },
        {
          label: "服务订单",
          value: "服务订单"
        },
        {
          label: "其他",
          value: "其他"
        }
      ],
      // 图片列表
      fileList: [],
      // 产品列表
      productList: [],
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 选中的数据
      selectedItemId: null,
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  watch: {
    activityDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    this.getAllProduct()
  },
  activated() {
    this.getList()
  },
  methods: {
    handleLoad: throttle(function () {
      if(!this.queryParams.hasNextPage) {
        return false
      }
      this.queryParams.pageNum += 1
      this.getList({ isConnect: true })
    }, 2000),
    // 添加工单的回调
    addHandler(result) {
      updateDataApi({
        ...this.form,
        workorderId: result.data
      }).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.getList()
          this.$router.push({name: "WorkorderDetail", query: {workorderId: result.data}})
          this.workorderVisible = false
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    // 创建工单的弹窗
    createOrderDialog(row) {
      this.form = {...row}
      this.workorderVisible = true
    },
    // 单选选中数据
    handleRowChange(row) {
      // debugger;
      if (row) {
        this.selectedItemId = row.id;
      }
    },
    // 关联的回调
    relevanceHandler() {
      if (this.selectedItemId == null || this.selectedItemId === 0) {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '请至少选择一条数据!'
        });
        return;
      }
      updateDataApi({
        ...this.form,
        workorderId: this.selectedItemId
      }).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.getList()
          this.relevanceVisible = false
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    // 获取数据
    async getList2() {
      this.loading2 = true
      const res = await getWorkorderListApi(this.queryParams2)
      if (res.code === 200) {
        this.tableData2 = res.data.list ?? []
        this.total2 = res.data.total
      }
      this.loading2 = false
    },
    // 查看图片
    handlePictureCardPreview(url) {
      this.imgDialogUrl = this.env + url
      this.imgDialogVisible = true;
    },
    // 获取全部产品
    async getAllProduct() {
      const res = await getAllProductApi({})
      if (res.code === 200) {
        this.productList = res.rows ?? []
      }
    },
    // 上传全部图片
    async uploadImg() {
      const urlList = (this.fileList ?? []).filter(i => !i.raw).map(i => i.url)
      const list = (this.fileList ?? []).filter(i => i.raw).map((item) => {
        const formData = new FormData()
        formData.append('file', item.raw)
        return uploadImgApi(formData)
      })

      const imgList = (await Promise.all(list) ?? []).map(item => item?.fileName ?? "") ?? []
      this.form.image = [...urlList, ...imgList].join(',')
    },
    // 删除图片
    handleRemove(_, fileList) {
      this.fileList = fileList
    },
    // 选中图片
    handleChange(_, fileList) {
      this.fileList = fileList
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList(options) {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        if(options?.isConnect) {
          const list = res.data.list ?? []
          this.tableData = [...this.tableData, ...list]
        } else {
          this.tableData = res.data.list ?? []
        }

        this.total = res.data.total ?? 0
        this.queryParams.pages = res.data.pages ?? 0
        this.queryParams.hasNextPage = res.data.hasNextPage
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 搜索的回调
    searchHandler2() {
      this.selectedRows = null
      this.queryParams2.pageNum = 1
      this.getList2()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 关联工单的弹窗
    relevanceDialog(row) {
      this.form = {...row}
      this.relevanceVisible = true
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {...row}
        this.fileList = ((row.image ?? "").split(',') ?? []).filter(i => i).map(item => ({name: item, url: item}))
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.form = {...this.$options.data().form}
          this.$refs.upload.clearFiles()
          this.fileList = []
        }

        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/activity/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `activities_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.uploadImg()
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs['formRef'].resetFields();
        this.$refs.upload.clearFiles()
        this.fileList = []
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.activityDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">
.img-box {
  display: flex;
  align-items: center;
}

.justify-content {
  justify-content: center;
}

.infinite-list {
  padding: 0;

  .infinite-list-item {
    margin: 8px 0;
    list-style: none;
  }

  .cus_text {
    & > div {
      margin: 10px auto;

      & > span:first-child {
        display: inline-block;
        width: 80px;
        font-weight: bolder;
        text-align: right;
        margin-right: 8px;
      }
    }
  }

  .flex {
    display: flex;
  }

  .items-center {
    align-items: center;
  }

  .flex-1 {
    flex: 1;
  }
}
</style>
